<?php 
include_once dirname(dirname(__FILE__))."/common.php";
\ns_core\m_load::load("ns_core.m_config");
/**
 * linux|windows mediainfo 查询 
 * @author pan.liang
 * @example m_medium::analyze_file(dirname(__FILE__).'/20180321175712.txt')
 * @return 
 */
class m_medium extends m_config
{
    /**
     * 文件格式包含
     * @var unknown
     */
    public static $arr_file_format = array(
        'ts',
        'mp3',
        'mp4',
        'mpg',
        'flv',
        'wma',
        'm2t',
        'kux',
        'wmv',
        'm2ts',
        'mov',
        'mpeg',
        'rmvb',
        'avi',
    );
    
    /**
     * 错误的数组文件
     * @var unknown
     */
    public static $arr_error_file = null;
    
    /**
     * 片源文件信息
     * @var unknown
     */
    public static $arr_right_data = array(
        'cp_data'=>null,
        'media_data'=>null,
    );
    
    /**
     * 允许分析的数量
     * @var unknown
     */
    public static $analyze_count = 800;
    
    /**
     * 验证TXT文件的可用性
     * @param unknown $file_path
     */
    public static function check_txt_file($file_path)
    {
        $file_path = trim($file_path);
        if(strlen($file_path) <1)
        {
            return self::return_data(1,"传入参数为空");
        }
        if(!file_exists($file_path))
        {
            return self::return_data(1,"传入分析文件不存在,文件路径{$file_path}");
        }
        $arr_pathinfo = pathinfo($file_path);
        if(!isset($arr_pathinfo['extension']) || strlen($arr_pathinfo['extension']) <1)
        {
            return self::return_data(1,"传入分析文件扩展名为空,文件路径{$file_path}");
        }
        if(strtolower(trim($arr_pathinfo['extension'])) != 'txt')
        {
            return self::return_data(1,"传入分析文件非法只解析TXT文件,文件路径{$file_path}");
        }
        return self::return_data(0,"ok");
    }
    
    /**
     * 验证片源文件的可用性
     * @param unknown $file_path
     */
    public static function check_media_file($media_file_path,$encoding='UTF8')
    {
        $media_file_path = trim($media_file_path);
        if(strlen($media_file_path) <1)
        {
            return self::return_data(1,"传入参数为空");
        }
        #TODO $media_file_path编码
//         if(!file_exists($media_file_path))
//         {
//             return self::return_data(1,"传入片源文件不存在,文件路径{$media_file_path}");
//         }
        $arr_pathinfo = pathinfo($media_file_path);
        if(!isset($arr_pathinfo['extension']) || strlen($arr_pathinfo['extension']) <1)
        {
            return self::return_data(1,"传入片源文件扩展名为空,文件路径".var_export($arr_pathinfo,true));
        }
        if(!in_array(strtolower(trim($arr_pathinfo['extension'])), self::$arr_file_format))
        {
            return self::return_data(1,"传入片源文件非法只解析[".implode(',', self::$arr_file_format)."]文件,片源文件扩展{$arr_pathinfo['extension']}");
        }
        return self::return_data(0,"ok");
    }
    
    /**
     * 分析片源文件  遍历TXT
     * @param unknown $file_path
     */
    public static function analyze_file($file_path,$disk_path)
    {
        $disk_path = str_replace('//', '/', $disk_path);
        $disk_path = str_replace('\\\\', '/', $disk_path);
        $disk_path = trim($disk_path,'/');
        $disk_path = explode('/', $disk_path);
        $count_path = count($disk_path);
        $count_path = $count_path > 0 ? $count_path : 0;
        $result_check = self::check_txt_file($file_path);
        if($result_check['ret'] !=0)
        {
            return $result_check;
        }
        $is_left_flag = true;
        $data_file = fopen($file_path, 'r');
        $locked = flock($data_file, LOCK_EX + LOCK_NB);
        $count = 0;
        while (!feof($data_file))
        {
            $line_item = fgets($data_file);
            if (!$line_item)
            {
                continue;
            }
            $line_item = trim($line_item);
            if(strlen($line_item) <1)
            {
                continue;
            }
            $count++;
            if($count >self::$analyze_count)
            {
                ob_start();
                fpassthru($data_file);
                $is_left_flag = false;
                break;
            }
            self::analyze_medium_file($line_item,$count_path);
//             $result_check_media_file = self::check_media_file($line_item);
//             if($result_check_media_file['ret']!=0)
//             {
//                 self::$arr_error_file[] = $line_item;
//                 continue;
//             }
//             $result_analyze = self::analyze_media_file_info($line_item,$count_path);
//             if($result_analyze['ret']!=0)
//             {
//                 self::$arr_error_file[] = $line_item;
//             }
        }
        flock($data_file, LOCK_EX + LOCK_NB);
        fclose($data_file);
        $left_content = $is_left_flag ? "" : ob_get_clean();
        if(strlen($left_content) >0)
        {
            @file_put_contents($file_path, $left_content);
        }
        else
        {
            @unlink($file_path);
        }
        return self::return_data(0,"Ok",array('right_data'=>self::$arr_right_data,'error_data'=>self::$arr_error_file));
    }
    
    
    public static function analyze_medium_file($line_item,$disk_path)
    {
        $disk_path = str_replace('\\\\', '/', $disk_path);
        $disk_path = str_replace('//', '/', $disk_path);
        $disk_path = trim($disk_path,'/');
        $disk_path = explode('/', $disk_path);
        $count_path = count($disk_path);
        $count_path = $count_path > 0 ? $count_path : 0;
        $result_check_media_file = self::check_media_file($line_item);
        if($result_check_media_file['ret']!=0)
        {
//             self::$arr_error_file[] = $line_item;
//             continue;
            return self::return_data(0,"Ok",array('right_data'=>self::$arr_right_data,'error_data'=>self::$arr_error_file));
        }
        $result_analyze = self::analyze_media_file_info($line_item,$count_path);
        if($result_analyze['ret']!=0)
        {
            self::$arr_error_file[] = $line_item;
            return self::return_data(0,"Ok",array('right_data'=>self::$arr_right_data,'error_data'=>self::$arr_error_file));
        }
        return self::return_data(0,"Ok",array('right_data'=>self::$arr_right_data,'error_data'=>self::$arr_error_file));
    }
    
    /**
     * 分析片源文件
     * @param unknown $media_file_path
     */
    public static function analyze_media_file_info($media_file_path,$count_path=0)
    {
        $media_file_path = trim(trim(trim(str_replace("\\", '/', str_replace("\\", '/', str_replace("//", '/', str_replace("//", '/', $media_file_path)))),'/'),'\\'));
        if(strlen($media_file_path) <1)
        {
            return self::return_data(1,"替换后的数据有误，不在处理");
        }
        $arr_path = explode("/", $media_file_path);
        if(!is_array($arr_path) || empty($arr_path) || !is_array($arr_path))
        {
            return self::return_data(1,"explode后非数组不在处理");
        }
        if(count($arr_path) <3)
        {
            return self::return_data(1,"explode后非数组层级<3,不处理");
        }
        if($count_path >0)
        {
            for ($i=0;$i<$count_path;$i++)
            {
                array_shift($arr_path);
            }
        }
        $str_cp_name = array_shift($arr_path);
        $str_cp_id = MD5($str_cp_name);
        
        if(!isset(self::$arr_right_data['cp_data'][$str_cp_id]))
        {
            self::$arr_right_data['cp_data'][$str_cp_id] = $str_cp_name;
        }
        $arr_pathinfo = pathinfo($media_file_path);
        $arr_pathinfo_1 = pathinfo(implode('/', $arr_path));
        $result_asset_info = self::make_media_assist_name_id($arr_path);
        $str_extension = (isset($arr_pathinfo['extension']) && strlen($arr_pathinfo['extension']) >0) ? trim(strtolower($arr_pathinfo['extension'])) : '';
        $str_dirname = (isset($arr_pathinfo['dirname']) && strlen($arr_pathinfo['dirname']) >0) ? trim(strtolower($arr_pathinfo['dirname'])) : '';
        $str_filename = (isset($arr_pathinfo_1['filename']) && strlen($arr_pathinfo_1['filename']) >0) ? trim(strtolower($arr_pathinfo_1['filename'])) : '';
        $result_asset_index = self::make_media_index(trim($str_dirname.'/'.$str_filename,'/'));
        self::$arr_right_data['media_data'][] = array(
            'id'=>md5($media_file_path),
            'cp_id'=>$str_cp_id,
            'filename'=>$str_filename,
            'extension'=>$str_extension,
            'index'=>$result_asset_index['data_info']['index'],
            'index_state'=>$result_asset_index['data_info']['state'],
            'asset_id'=>$result_asset_info['data_info']['id'],
            'asset_name'=>$result_asset_info['data_info']['name'],
            'asset_path_name'=>$result_asset_info['data_info']['path_name'],
            'url'=>$media_file_path,
        );
        return self::return_data(0,'ok');
    }
    
    /**
     * 获取片源文件的媒资信息
     * @param unknown $arr_path
     */
    public static function make_media_assist_name_id($arr_path)
    {
        $media_assist_id=$media_path_assist_name=$media_assist_name='';
        if(!is_array($arr_path) || empty($arr_path))
        {
            return self::return_data(0,"生成媒资名称失败,路径为空，不在解析，路径:".implode('/', $arr_path),array('id'=>$media_assist_id,'name'=>$media_assist_name,'path_name'=>$media_path_assist_name));
        }
        $temp_path=null;
        $temp_data = null;
        foreach ($arr_path as $value)
        {
            $str_chinese = '';
            preg_match_all('/[\x{4e00}-\x{9fff}]+/u', $value, $matches);
            if(isset($matches[0]) && is_array($matches[0]) && !empty($matches[0]))
            {
                $str_chinese = implode('', $matches[0]);
            }
            $str_chinese = str_replace(' ', '', $str_chinese);
            if(strlen($str_chinese) <1)
            {
                continue;
            }
            $temp_data[] = $str_chinese;
        }
        if(!empty($temp_data) && is_array($temp_data))
        {
            $media_path_assist_name = implode('-', $temp_data);
            $media_assist_id = md5($media_path_assist_name);
            $media_assist_name = array_pop($temp_data);
        }
        return self::return_data(0,"ok",array('id'=>$media_assist_id,'name'=>$media_assist_name,'path_name'=>$media_path_assist_name));
    }
    
    /**
     * 获取片源文件的分集信息
     * @param unknown $str_media_path
     */
    public static function make_media_index($str_media_path)
    {
        $arr_path = explode('/',trim($str_media_path));
        $state = $media_index = 0;
        if(!is_array($arr_path) || empty($arr_path))
        {
            return self::return_data(0,"生成媒资名称失败,路径为空，不在解析，路径:".implode('/', $arr_path),array('index'=>1,'state'=>1));
        }
        $temp_data = null;
        foreach ($arr_path as $value)
        {
            preg_match_all('/[0-9]+/', $value, $matches);
            if(isset($matches[0]) && is_array($matches[0]) && !empty($matches[0]))
            {
                foreach ($matches[0] as $temp_index)
                {
                    $temp_index = trim(ltrim($temp_index));
                    if(strlen($temp_index)<1)
                    {
                        continue;
                    }
                    if($temp_index <1)
                    {
                        continue;
                    }
                    $temp_data[] = $temp_index;
                }
            }
        }
        if((preg_match('/名侦探柯南/', $str_media_path) || preg_match('/樱桃小丸子/', $str_media_path)) && !empty($temp_data) && is_array($temp_data))
        {
            $media_index = (int)array_pop($temp_data);
        }
        else if(!empty($temp_data) && is_array($temp_data))
        {
            $count = count($temp_data);
            for($i=0;$i<1;$i++)
            {
                $temp_index = array_pop($temp_data);
                if((int)$temp_index <250 && (int)$temp_index >0)
                {
                    $media_index = (int)$temp_index;
                    break;
                }
            }
        }
        else
        {
            $media_index = 1;
            $state = 1;
        }
        if((int)$media_index >=250 || (int)$media_index <=0)
        {
            $media_index = 1;
            $state = 1;
        }
        return self::return_data(0,"ok",array('index'=>$media_index,'state'=>$state));
    }
}